<?php
class MultiFileWidget extends CInputWidget
{
    public $allowDeleteAll = true;
    public $fileOptions = array();

    public function run()
    {
        $this->htmlOptions['id'] = $this->getId();
        if (isset($this->htmlOptions['class'])) {
            $this->htmlOptions['class'] .= ' multi-file';
        }
        else {
            $this->htmlOptions['class'] = 'multi-file';
        }
        echo CHtml::openTag('div', $this->htmlOptions);
        if (is_array($this->model) && count($this->model)) {
            foreach ($this->model as $index => $model) {
                echo CHtml::openTag('div', array('class' => 'multi-file-row'));
                echo CHtml::activeHiddenField($model, '[' . $index . ']id');
                $fileOptions = array(
                    'model' => $model,
                    'attribute' => '[' . $index . ']' . $this->attribute,
                );
                $fileOptions = CMap::mergeArray($fileOptions, $this->fileOptions);
                $this->widget('Gallery.components.FileWidget', $fileOptions);
                echo '<b>Name</b><br />'.CHtml::activeTextField($model,'['.$index.']name',array('class'=>'photo-name')).'<br />';
                echo '<b>Link</b><br />'.CHtml::activeTextField($model,'['.$index.']website',array('class'=>'photo-link')).'<br />';
                echo '<b>Description</b><br />'.CHtml::activeTextArea($model,'['.$index.']description',array('class'=>'photo-description'));
                echo CHtml::openTag('div', array('class' => 'file-actions'));
                echo CHtml::link('Add', '#', array('class' => 'add-file'));
                echo CHtml::link('Delete', '#', array('class' => 'delete-file'));
                echo CHtml::closeTag('div');
                echo CHtml::closeTag('div');
            }
        }
        else {
            if (count($this->value) <= 0) {
                $this->value = array('');
            }
            if (strpos($this->name, '[]') === false) {
                $this->name = $this->name . '[]';
            }
            foreach ($this->value as $index => $value) {
                echo CHtml::openTag('div', array('class' => 'multi-file-row'));
                $this->widget('Gallery.components.FileWidget', array(
                    'name' => $this->name,
                    'value' => $this->value[$index],
                ));
                echo CHtml::openTag('div', array('class' => 'file-actions'));
                echo CHtml::link('Add', '#', array('class' => 'add-file'));
                echo CHtml::link('Delete', '#', array('class' => 'delete-file'));
                echo CHtml::closeTag('div');
                echo CHtml::closeTag('div');
            }
        }
        echo CHtml::closeTag('div');
        $this->registerScripts();
    }

    public function registerScripts()
    {
        $script = "
var allow_delete_all = " . (boolean)$this->allowDeleteAll . ";
jQuery.fn.updateIndex = function(obj)
{
    var html = obj.html();
    var data = [];
    jQuery('.file').each(function(){
        var name = jQuery('input:first', this).attr('name');
        name = name.replace(/.*\[(\d+)\]\[{$this->attribute}\]/, '\$1');
        data.push(parseInt(name));
    });
    data.sort();
    var max = data.pop()+1;
    html = html.replace(/\[(\d+)\]/g, '['+max+']');
    html = html.replace(/_(\d+)_/g, '_'+max+'_');
    obj.html(html);
    jQuery.fn.updateOrder(obj);
}
jQuery.fn.updateOrder = function(obj)
{
    var children = obj.closest('.multi-file').children();
    $.each(children, function(index, item){
        var item_index = index;
        $(item).find('input').each(function(){
            var elm = $(this);
            var elm_name = elm.attr('name');
            elm_name = elm_name.replace(/\[(\d+)\]/g, '['+item_index+']');
            var elm_id = elm.attr('id');
            elm_id = elm_id.replace(/_(\d+)_/g, '_'+item_index+'_');
            elm.attr('name',elm_name);
            elm.attr('id',elm_id);
        });
        $(item).find('textarea').each(function(){
            var elm = $(this);
            var elm_name = elm.attr('name');
            elm_name = elm_name.replace(/\[(\d+)\]/g, '['+item_index+']');
            var elm_id = elm.attr('id');
            elm_id = elm_id.replace(/_(\d+)_/g, '_'+item_index+'_');
            elm.attr('name',elm_name);
            elm.attr('id',elm_id);
        });
    });
}
jQuery('.add-file').live('click', function(){
    var row = jQuery(this).closest('.multi-file-row');
    var new_row = row.clone();
    row.after(new_row);
    jQuery.fn.updateIndex(new_row);
    new_row
        .find('.deselect-file').trigger('click')
        .end()
        .find('.select-file').trigger('click')
        .end()
        .find('input:first').val('')
        .end()
        .find('input.photo-name, input.photo-link, textarea.photo-description').val('');
    jQuery.fn.can_delete();
    return false;
});
jQuery('.delete-file').live('click', function(){
    if (allow_delete_all && jQuery('.multi-file-row').size() <= 1)
    {
        jQuery(this).closest('.multi-file-row')
            .find('.deselect-file').trigger('click');
        return false;
    }
    jQuery(this).closest('.multi-file-row').remove();
    jQuery.fn.can_delete();
    jQuery.fn.updateOrder($('.multi-file-row:first'));
    return false;
});

jQuery.fn.can_delete = function()
{
    if (jQuery('.multi-file-row').size() > 1)
    {
        jQuery('.multi-file-row .delete-file').show();
    }
    else
    {
        if (! allow_delete_all)
            jQuery('.multi-file-row .delete-file').hide();
    }
}
jQuery.fn.can_delete();
";
        Yii::app()->clientScript->registerScript(__CLASS__ . '#MultiFile', $script);
        $baseUrl = Yii::app()->assetManager->publish(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'multi_file');
        echo CHtml::css("
.multi-file {overflow: hidden;}
.multi-file-row img {border: 1px solid #ccc; border-radius: 5px; padding: 1px;}
.multi-file-row {overflow: hidden; margin: 20px 0; /*position: relative;*/ width: 110px; float: left; margin-right : 10px;}
.multi-file-row .deselect-file {display: none !important;}
.multi-file-row .add-file {background: url({$baseUrl}/add.png) no-repeat center center; display: block; height: 16px; width: 16px; float: left; text-indent: 9999px;}
.multi-file-row .delete-file {background: url({$baseUrl}/remove.png) no-repeat center center; display: block; height: 16px; width: 16px; float: left; text-indent: 9999px; margin-left: 10px;}
");
    }
}
